<template>
	<el-card shadow="hover" class="layout-padding-auto">
		<div class="system-user-search mb15">
			<el-input size="default" placeholder="请输入用户密钥" v-model="state.tableData.param.param.id.val"
				style="max-width: 180px"></el-input>
			<el-input size="default" placeholder="请输入用户账号" v-model="state.tableData.param.param.user_name.val"
				style="max-width: 180px"> </el-input>
			<el-input size="default" placeholder="请输入用户昵称" v-model="state.tableData.param.param.nickname.val"
				style="max-width: 180px"> </el-input>
			<el-button size="default" type="primary" @click="onHandleCurrentChange(1)">
				<el-icon>
					<ele-Search />
				</el-icon>
				查询
			</el-button>
		</div>
		<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%">
			<el-table-column prop="id" label="ID" show-overflow-tooltip width="80px"></el-table-column>
			<el-table-column prop="user_img" label="头像" width="80px">
				<template #default="scope">
					<el-avatar :src="state.imgUrl + scope.row.picture">
						<img :src="chatHealth" />
					</el-avatar>
				</template>
			</el-table-column>
			<el-table-column prop="user_name" label="用户账号" show-overflow-tooltip></el-table-column>
			<el-table-column prop="nickname" label="用户昵称" show-overflow-tooltip></el-table-column>
			<el-table-column prop="role_name" label="关联角色" show-overflow-tooltip>

				<template #default="scope">
					{{ scope.row.role_ids == '1' ? '管理员' : '普通用户' }}
				</template>
			</el-table-column>
			<el-table-column label="所属公司" show-overflow-tooltip>
				<template #default="scope">
					{{ scope.row.company_name || '公海用户' }}
				</template>
			</el-table-column>
			<el-table-column prop="status" label="用户状态" show-overflow-tooltip>
				<template #default="scope">
					<el-tag type="success" v-if="scope.row.status == '1'" @click="setStatus(0, scope.row)"
						style="cursor: pointer;">启用</el-tag>
					<el-tag type="info" v-else @click="setStatus(1, scope.row)" style="cursor: pointer;">禁用</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" width="180px">
				<template #default="scope">
					<span>{{ dateFormatYMDHMS(scope.row.create_time * 1000) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="150"
				v-auths="['/member/user/conf', '/member/user/edit', '/member/user/del']">
				<template #default="scope">
					<el-button size="small" text type="primary" v-auth="'/member/user/conf'"
						@click="onOpenEditUser('conf', scope.row)">配置</el-button>
					<el-button size="small" text type="primary" v-auth="'/member/user/edit'"
						@click="onOpenEditUser('edit', scope.row)">修改</el-button>
					<el-button size="small" text type="primary" v-auth="'/member/user/del'"
						@click="onRowDel(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
			:pager-count="5" :page-sizes="[10, 20, 30]" v-model:current-page="state.tableData.param.page" background
			v-model:page-size="state.tableData.param.limit" layout="total, sizes, prev, pager, next, jumper"
			:total="state.tableData.total">
		</el-pagination>
	</el-card>
	<UserDialog ref="userDialogRef" @refresh="getTableData()" />
	<ConfigDialog ref="userConfigDialogRef" />
</template>

<script setup name="memberuser">
import { defineAsyncComponent, reactive, onMounted, ref ,nextTick } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { memberApi } from '/@/api/member/index';
import { commApi } from '/@/api/comm/index';
// 引入组件
const UserDialog = defineAsyncComponent(() => import('/@/views/member/user/dialog.vue'));
const ConfigDialog = defineAsyncComponent(() => import('/@/views/member/user/dialogConfig.vue'));
import chatHealth from '/@/assets/error_tou.png'
import commonFunction from '/@/utils/commonFunction';
const { dateFormatYMDHMS } = commonFunction();
const paramOp = {
	nickname: '%%',
	id: '**'
}
// 定义变量内容
const userDialogRef = ref();
const userConfigDialogRef = ref();
const state = reactive({
	imgUrl: import.meta.env.VITE_IMG_URL,
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			param: {
				id: {},
				user_name: {},
				nickname: {},
				company_ids: {},
				inviter:{}
			},
			page: 1,
			limit: 10,
		},
	},
	platsData: {
		company: [],
		palt: [],
		paltform: []
	},
});
const setInviter = (inviter) => {
	state.tableData.param.param.inviter.val = inviter
	onHandleCurrentChange(1)
}
const setStatus = (status, row) => {
	let label = ''
	if (status == 0) {
		label = `此操作将禁用账户名称：“${row.nickname}”，是否继续?`
	} else {
		label = `此操作将启用账户名称：“${row.nickname}”，是否继续?`
	}
	ElMessageBox.confirm(label, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				let res = await memberApi().setStatus({ status, id: row.id })
				if (res.code == 0) {
					getTableData()
				}
			} catch (error) {

			}
		})
		.catch(() => { });

}
// 初始化表格数据
const getTableData = () => {
	state.tableData.loading = true;
	for (let key in state.tableData.param.param) {
		if (state.tableData.param.param[key].val && state.tableData.param.param[key].val !== '') {
			state.tableData.param.param[key].op = paramOp[key] || '='
		} else {
			state.tableData.param.param[key] = {}
		}
	}
	memberApi().index(state.tableData.param).then(res => {
		state.tableData.data = res.data.list;
		state.tableData.total = res.data.total;
		state.tableData.loading = false;
	})
};
// 打开新增用户弹窗
const onOpenAddUser = (type) => {
	userDialogRef.value.openDialog(type);
};
// 打开修改和配置用户弹窗
const onOpenEditUser = (type, row) => {
	if (type === 'conf') {
		userConfigDialogRef.value.openDialog(row);
		return;
	}
	userDialogRef.value.openDialog(type, row);
};
// 删除用户
const onRowDel = (row) => {
	ElMessageBox.confirm(`此操作将永久删除账户名称：“${row.nickname}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			memberApi().del({ ids: row.id }).then(res => {
				getTableData();
				ElMessage.success('删除成功');
			})
		})
		.catch(() => { });
};
// 分页改变
const onHandleSizeChange = (val) => {
	state.tableData.param.limit = val;
	getTableData();
};
// 分页改变
const onHandleCurrentChange = (val) => {
	state.tableData.param.page = val;
	getTableData();
};
// 初始化公司数据
const getCompanyData = () => {
	commApi().getPlats({ paltform_type: 3 }).then(async res => {
		state.platsData = res.data
		await nextTick() // 等待下一个DOM更新周期
		if (userDialogRef.value) {
			userDialogRef.value.state.platsData = res.data
		}
	})
};
// 页面加载时
onMounted(() => {
	getCompanyData()
});
// 暴露变量
defineExpose({
	setInviter
});
</script>

<style scoped lang="scss">
.system-user-container {
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;

		.el-table {
			flex: 1;
		}
	}
}
</style>
